// token
const jwtKoa = require('koa-jwt')
const jwt = require('jsonwebtoken')

let { cookieKey: cookie, secret, unless, maxAge  } = require('../app_conf')['token']

const fs = require('fs')
const path = require('path')

module.exports = {

    /**
     * 绑定中间件
     * @param app
     */    

    bindToken: async (app) =>{
        app.use(jwtKoa({secret, cookie}).unless(unless))
    },  

    /**
     * 生成token
     * @param data 载荷数据
     * 
     */
    
    signToken: (data) =>{

        return jwt.sign(data, secret, { expiresIn: maxAge })
    },
    
    /**
     * 解析token
     * @param token
     * @return 解析后数据，添加时间戳属性, exp: 到期时间, iat:创建时间
     */
    
    tokenVerify: (token) =>{

        let data = jwt.verify(token, secret)

        Object.assign(data, {expTime:  new Date(data.exp * 1000), iatTime: new Date(data.iat * 1000)})

        return  data 
        
    },

    /**
     *  无tonken错误处理
     */
    
    tokenErr:  async (ctx, next) =>{

        await  next().catch(err =>{
    
            if(err.status === 401){
    
                ctx.status = 401;
                ctx.body = {
                    status: 401,
                    msg: '请提交有效token'
                }
                
            }else{ throw err }
            
        })
        
    },

   
    
    
}
